package handler

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var article []model.Good

	err := model.DB.Find(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
func Look(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	var articl model.Good
	redis_key := "listss"
	createDta, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if createDta == "" {
		model.DB.Offset(offset).Limit(size).First(&articl)
		jsonData, _ := json.Marshal(articl)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(createDta), &articl)
	}

	var total int64
	model.DB.Model(model.Good{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  articl,
		"total": total,
	})
	return
}

func Create(c *gin.Context) {
	title := c.PostForm("title")
	count := c.PostForm("count")
	now_count := c.PostForm("now_count")
	if title == "" || count == "" || now_count == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段部门能为空",
		})
		return
	}

	var data model.Good
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "添加成功",
	})
	return
}
